//
//  VC5MediaPlayer.swift
//  ChapterAll
//
//  Created by Kevin on 2020/4/25.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit
import AVKit

class VC5MediaPlayer: UIViewController {
    
    var playerItem:AVPlayerItem?
    var mplayer:AVPlayerViewController?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let file = Bundle.main.url(forResource: "huaxia", withExtension: ".mp4")
        playerItem = AVPlayerItem(url: file!)
        
        mplayer = AVPlayerViewController()
        mplayer?.player = AVPlayer(playerItem: playerItem)
        mplayer?.videoGravity = .resizeAspect
        mplayer?.showsPlaybackControls = true
        mplayer?.view.frame = CGRect(x: 0, y: 100, width: view.frame.width, height: 400)
        view.addSubview((mplayer?.view)!)
        
        
        // 监听loadedTimeRanges属性来监听缓冲进度更新
        playerItem?.addObserver(self, forKeyPath: "loadedTimeRanges", options: .new, context: nil)
        // 监听status属性进行播放
        playerItem?.addObserver(self, forKeyPath: "status", options: .new, context: nil)
    }
    
    // 将秒转成时间字符串的方法，因为我们将得到秒。
    func formatPlayTime(seconds: Float64) -> String {
        let min = Int(seconds / 60)
        let sec = Int(seconds.truncatingRemainder(dividingBy: 60))
        return String(format: "%02d:%02d", min, sec)
    }
    
    // 计算当前的缓冲进度
    func availableDurationWithplayerItem() -> TimeInterval {
        guard let loadedTimeRanges = mplayer!.player?.currentItem?.loadedTimeRanges,
            let first = loadedTimeRanges.first else {
                fatalError()
        }
        let timeRange = first.timeRangeValue
        let startSeconds = CMTimeGetSeconds(timeRange.start) // 本次缓冲起始时间
        let durationSecound = CMTimeGetSeconds(timeRange.duration)// 缓冲时间
        let result = startSeconds + durationSecound// 缓冲总长度
        return result
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        guard let obj = object as? AVPlayerItem else {
            return
        }
        guard let path = keyPath else {
            return
        }
        if path == "status" {
            if obj.status == .readyToPlay {
                mplayer!.player?.play()
                print("正在播放...，视频总长度:\(self.formatPlayTime(seconds: CMTimeGetSeconds(obj.duration)))")
            }else if obj.status == .failed || obj.status == .unknown {
                print("播放出错")
            }
        }else if keyPath == "loadedTimeRanges" {
            let loadedTime = availableDurationWithplayerItem()
            print("当前加载进度\(loadedTime)")
        }
    }
    
    deinit {
        playerItem?.removeObserver(self, forKeyPath: "status")
        playerItem?.removeObserver(self, forKeyPath: "loadedTimeRanges")
    }
}
